package hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

@Controller // This means that this class is a Controller
@RequestMapping(path = "/demo") // This means URL's start with /demo (after Application path)
public class MainController {
  @Autowired // This means to get the bean called userRepository
  // Which is auto-generated by Spring, we will use it to handle the data
  private UserRepository userRepository;

  @PostMapping(path = "/add") // Map ONLY POST Requests
  public @ResponseBody String addNewUser(
      @RequestParam String name, @RequestParam String email, @RequestParam String tags) {
    // @ResponseBody means the returned String is the response, not a view name
    // @RequestParam means it is a parameter from the GET or POST request

    User user = new User();
    user.setName(name);
    user.setEmail(email);
    user.setTags(tags);
    user.setLastUpdated(System.currentTimeMillis());
    userRepository.save(user);
    return "Saved. User id:" + user.getId();
  }

  @PutMapping(path = "/update") // Map ONLY POST Requests
  public @ResponseBody String updateUser(
      @RequestParam Integer id,
      @RequestParam String name,
      @RequestParam String email,
      @RequestParam String tags) {
    User user = userRepository.findById(id).get();
    user.setName(name);
    user.setEmail(email);
    user.setTags(tags);
    user.setLastUpdated(System.currentTimeMillis());
    userRepository.save(user);
    return "Updated. User id:" + user.getId();
  }

  @GetMapping(path = "/all")
  public @ResponseBody Iterable<User> getAllUsers() {
    // This returns a JSON or XML with the users
    return userRepository.findAll();
  }

  @DeleteMapping(path = "/delete")
  public @ResponseBody String deleteUser(@RequestParam Integer id) {
    User user = userRepository.findById(id).get();
    user.setLastUpdated(System.currentTimeMillis());
    user.setIsDeleted(true);
    userRepository.save(user);
    return "Deleted. User id:" + user.getId();
  }
}
